<template>
  <div class="shop">
    <el-form :inline="true" size="mini" class="form">
      <el-form-item>
        <el-button class="addBtn" type="primary" @click="linkcodes()">批量导出收款码</el-button>
      </el-form-item>
      <el-form-item>
        <el-button class="addBtn" type="primary" @click="isShowDetail = true">新增</el-button>
      </el-form-item>
    </el-form>
    <el-form :inline="true" size="mini" :model="form" class="form">
      <el-form-item>
        <template>
          <el-select v-model="form.isRelateShop" clearable style="width:120px" placeholder="是否关联商户">
            <el-option name="w" value="1" label="关联">
            </el-option>
            <el-option name="w" value="3" label="不关联">
            </el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label='绑定时间:'>
        <el-date-picker v-model="form.bindStartTime" type="date" style="width:136px" value-format="yyyy-MM-dd"
          placeholder="选择开始时间">
        </el-date-picker>
        ~
        <el-date-picker v-model="form.bindEndTime" type="date" style="width:136px" value-format="yyyy-MM-dd"
          placeholder="选择结束时间"></el-date-picker>
      </el-form-item>
      <el-form-item label='创建时间:'>
        <el-date-picker v-model="form.startTime" type="date" style="width:136px" value-format="yyyy-MM-dd"
          placeholder="选择开始时间">
        </el-date-picker>
        ~
        <el-date-picker v-model="form.endTime" type="date" style="width:136px" value-format="yyyy-MM-dd"
          placeholder="选择结束时间"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input class="input" style="width:125px" v-model="form.code" placeholder="收款码ID搜索" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input class="input" style="width:130px" v-model="form.shopId" placeholder="关联商户名搜索" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchShopMin">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width:100%" max-height="600" class="shop_table_list" :cell-style="tc"
      :header-cell-style="tccolor">
      <el-table-column prop="code" label="收款码ID"></el-table-column>
      <el-table-column label="收款码" width="160">
        <template slot-scope="scope">
          <div>
            <img @click="lookBigPicture(scope.row.code)" style="width: 30px;margin-left: 10px"
              src="../../../assets/images/20200602112954.png" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="关联客户"></el-table-column>
      <el-table-column label="创建时间" width="270">
        <template slot-scope="scope">
          <p>{{ parseTime(scope.row.createdAt) }}</p>
        </template>
      </el-table-column>
      <el-table-column label="关联时间" width="270" prop="bindAt">
        <template slot-scope="scope">
          <p>{{ parseTime(scope.row.bindAt) }}</p>
        </template>
        <!-- <template slot-scope="scope">
                    <p>{{scope.row.connect_at}}
                        <span v-if="scope.row.shop_id!=0"
                              class="ckil"
                              @click="ckil(scope.row)">
                            查看记录
                        </span>
                    </p>
                </template> -->
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="260">
        <template slot-scope="scope">
          <el-button size="mini"
            @click="scope.row.shopId ? openShopMinDetail(scope.row) : getsubCreateConnect(scope.row)">
            {{ !scope.row.shopId ? '关联商户' : '取消关联' }}
          </el-button>
          <el-button size="mini" type="danger" @click="linkcode(scope.row.codeUrl)">
            下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24">
      <div class="pagination">
        <el-pagination background @current-change="pageChange" :current-page="form.pageNum" :page-size="form.pageSize"
          layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </el-col>
    <jdialog title='新增收款码' :visible.sync="isShowDetail" width="600px">
      <span class="search_">新增数量：</span>
      <el-input class="input search_q" style="width:400px" placeholder="输入数量" v-model="num">
      </el-input>
      <div class="dialog-footer">
        <el-button size='mini' @click="isShowDetail = false">取 消</el-button>
        <el-button size='mini' type="primary" @click="subaddcode">新 增</el-button>
      </div>
    </jdialog>
    <!--关联商户-->
    <jdialog title="关联商户" :visible.sync="isCreateConnect" width="600px">
      <div style="padding-top:20px;">
        <span class="search_">关联商户搜索：</span>
        <div style="display:inline-block;width:400px;" class="input el-input el-input--mini el-input--suffix">
          <!-- <input @change="handleSelect(state,0)"
                                v-on:input="handleSelect(state,0)"
                            v-model="state" style="width:400px" type="text" autocomplete="off" placeholder="商户账号搜索" class="el-input__inner"> -->
          <el-select v-model="shopId" filterable remote reserve-keyword placeholder="请输入小店ID"
            :remote-method="getStateList" :loading="loading">
            <el-option v-for="item in stateIdList" :key="item.id" :label="item.id + item.name" :value="item.id">
            </el-option>
          </el-select>
        </div>

      </div>


      <div v-for="(item, i) in searchList" class="searchList" :key="i">
        <template>
          <el-checkbox v-model="checked"></el-checkbox>
        </template>
        <div>
          <el-row class="shop_info_dalog">
            <el-col>商户名称：{{ item.shop_name }}</el-col>
            <el-col>账号：{{ item.phone }}</el-col>
          </el-row>
          <el-row class="shop_info_dalog">
            <el-col>商户地址：{{ item.address }}</el-col>
          </el-row>
          <el-row class="shop_info_dalog">
            <el-col>入驻时间：{{ item.create_time }}</el-col>
          </el-row>
          <el-row class="shop_info_dalog">
            <el-col>邀请账号：{{ item.invitation_mobile }}</el-col>
          </el-row>
          <el-row class="shop_info_dalog">
            <el-col style="color: red">{{ msg }}</el-col>
          </el-row>
        </div>

      </div>
      <div class="dialog-footer">
        <el-button size='mini' @click="isCreateConnect = false">取 消</el-button>
        <el-button size='mini' type="primary" @click="subCreateConnect(searchList)">关联该商户</el-button>
      </div>
    </jdialog>
    <!--取消商户关联-->
    <jdialog title="取消商户关联" :visible.sync="isCreateConnectfalse" width="600px">
      <div v-for="(item, i) in searchList" class="searchList" :key="i">
        <div>
          <el-row class="shop_info_dalog">
            <el-col>当前已关联商户</el-col>
          </el-row>
          <el-row class="shop_info_dalog">
            <el-col>商品名称：{{ item.shop_name }}</el-col>
            <el-col>账号：{{ item.phone }}</el-col>
          </el-row>
          <el-row class="shop_info_dalog">
            <el-col>商品地址：{{ item.address }}</el-col>
          </el-row>
          <el-row class="shop_info_dalog">
            <el-col>入驻时间：{{ item.create_time }}</el-col>
          </el-row>
          <el-row class="shop_info_dalog">
            <el-col>邀请账号：{{ item.invitation_mobile }}</el-col>
          </el-row>

        </div>

      </div>
      <div class="dialog-footer">
        <el-button size='mini' @click="isCreateConnectfalse = false">手滑,点错了</el-button>
        <el-button size='mini' type="primary" @click="getcodedeleteconnect()">取消该商户关联</el-button>
      </div>
    </jdialog>
    <!--关联记录-->
    <jdialog title="商户关联记录" :visible.sync="isconnectList" width="600px">
      <div class="shopN">
        <p>商户名称</p>
        <p>关联时间</p>
      </div>
      <div v-for="(item, i) in connectList" :key="i">
        <div class="shopN">
          <p>{{ item.shop_name }}</p>
          <p><span>{{ item.type == 1 ? '添加关联' : '删除关联' }}-----{{ item.created_at }}</span></p>
        </div>
      </div>
    </jdialog>

  </div>
</template>

<script>
// import errorImg from "@/assets/images/error_img.png";
// import uploadImg from "@/components/uploadImg";
// import {
//     codelist,
//     codedeleteconnect,
//     codedownload,
//     codecreateconnect,
//     codesearchshop,
//     codecreate,
//     codeconnectlog
// } from "@/api/goods";
import {
  shopCodeCreate,
  shopCodeUpdate,
  shopCodeUpdateShopIdDel, shopCodeLlist, shopCodeConnectLog, sellerList
} from '@/api/store'
import { API_BASE_URL } from "@/config";

export default {
  name: "codeManagement",
  components: {
    // uploadImg
  },
  mounted() {
    this.getProductListData();
  },
  data() {
    return {
      loading: false,
      stateIdList: [],
      isconnectList: false,
      connectList: [],
      is_export: '',
      num: '',
      url: '',
      code: '',
      isCreateConnectfalse: false,
      msg: '',
      getcode: '',
      checked: false,
      searchList: [],
      restaurants: [],
      //关联
      isCreateConnect: false,
      //展示详情
      isShowDetail: false,
      errorImg: '',
      // 选中的店铺ID
      shopId: 0,
      // 选中的二维码id
      selectid: 0,
      state: '',
      form: {
        isRelateShop: '',
        code: '',
        bindStartTime: '',
        bindEndTime: '',
        startTime: '',
        endTime: '',
        title: "",
        pageNum: 1,
        pageSize: 10

      },
      total: 0,
      tableData: [],
      //商品详情
      productDetail: {},
      //图片列表
      img_url: [],
      boardlist: []
    };
  },
  methods: {
    async ckil(e) {
      let url = "code=" + e.code
      let res = await codeconnectlog(url)
      this.connectList = res.data
      this.isconnectList = true
    },
    linkcodes() {
      this.is_export = 1
      this.getProductListData()
    },
    getUrlBase64(url) {
      return new Promise(resolve => {
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        let img = new Image()
        img.crossOrigin = 'Anonymous' //允许跨域
        img.src = url
        img.onload = function () {
          canvas.height = 300
          canvas.width = 300
          ctx.drawImage(img, 0, 0, 300, 300)
          let dataURL = canvas.toDataURL('image/png')
          canvas = null
          resolve(dataURL)
        }
      })
    },
    //新增
    async subaddcode() {
      let res = await shopCodeCreate({ num: Number(this.num) })
      this.getProductListData();
      this.$message.success(res.message)
      this.isShowDetail = false
    },
    async linkcode(code) {
      try {
        window.open(code, '_blank');
      } catch (error) {
        this.$message.error('下载失败，请稍后再试');
      }
      // try {
      //   let link = document.createElement('a');
      //   link.href = code;
      //   link.download = 'qrCode.png';
      //   link.click();
      // } catch (error) {
      //   this.$message.error('下载失败，请稍后再试');
      // }
      // let res = await codedownload({code})
      // this.url = res.data.url
      // this.getUrlBase64(res.data.url).then(base64 => {
      //     let link = document.createElement('a')
      //     link.href = base64
      //     link.download = 'qrCode.png'
      //     link.click()
      // })
    },
    // async handleSelect(url,id) {
    //     var urls = "phone=" + url+"&uid="+id
    //     let res = await codesearchshop(urls)
    //     this.searchList = res.data
    // },
    getsubCreateConnect(e) {
      this.isCreateConnect = true
      this.msg = ''
      this.searchList = []
      this.checked = false
      this.state = ''
      this.getcode = e
    },
    async subCreateConnect(item) {
      console.log(this.shopId, this.getcode)

      if (!this.shopId) {
        this.$message.error("请选择要关联商户")
      } else {
        let data = {
          id: this.getcode.id,
          shopId: this.shopId
        }
        let res = await shopCodeUpdate(data)
        if (res.code == '200') {
          this.$message.success(res.message)
          this.isCreateConnect = false
          this.msg = ''
          this.searchList = []
          this.checked = false
          this.state = ''
          this.getProductListData();

        } else {
          this.$message.error(res.message)
        }

      }
    },
    //查看大图
    async lookBigPicture(code) {
      let res = await codedownload({ code })
      this.$alert(`<img src=${res.data.url} />`, {
        dangerouslyUseHTMLString: true
      });
    },
    tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
    //获取商品列表
    async getProductListData() {
      let url;
      url = 'pageNum=' + this.form.pageNum +
        '&pageSize=' + this.form.pageSize
      this.form.code ? url += "&code=" + this.form.code : ''
      this.form.shopId ? url += "&shopId=" + this.form.shopId : ''
      this.form.isRelateShop ? url += "&isRelateShop=" + this.form.isRelateShop : ''
      this.form.bindStartTime ? url += "&bindStartTime=" + this.form.bindStartTime : ''
      this.form.bindEndTime ? url += "&bindEndTime=" + this.form.bindEndTime : ''
      this.form.startTime ? url += "&startTime=" + this.form.startTime : ''
      this.form.endTime ? url += "&endTime=" + this.form.endTime : ''

      // url ="code=" + this.form.code +
      //     "&shopId=" + this.form.shopId +
      //     "&isRelateShop=" + this.form.isRelateShop +
      //     '&bindStartTime=' + this.bindStartTime +
      //     '&bindEndTime=' + this.bindEndTime +
      //     "&startTime=" + this.form.startTime +
      //     "&endTime=" + this.form.endTime+
      //     "&code=" + this.form.code+


      let res = await shopCodeLlist(url);
      console.log(res)
      if (res.code === 200) {
        if (this.is_export == 1) {
          this.is_export = ''
          window.open(
            `${API_BASE_URL}/admin/download/zip/${res.data[1].download_token}`
          )
        } else {
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      }
    },
    //根据关键词重新获取小店
    searchShopMin() {
      this.getProductListData();
    },
    pageChange(page) {
      this.form.pageNum = page;
      this.getProductListData();
    },

    async isUseActivityChange(id, e) {
      console.log(e)
      if (e === 1) {
        //下架
        this.getDownProductData(id);
      } else {
        //上架
        this.getUpProductData(id);
      }
    },
    // //上架商品
    // async getUpProductData(id) {
    //     let res = await adupdatestatus({id, status: 0});
    //     if (res.code === 10000) {
    //         this.$message.success("启用成功");
    //         this.getProductListData();
    //     } else {
    //         this.$message.error(res.message);
    //     }
    // },
    // //下架商品
    // async getDownProductData(id) {
    //     let res = await adupdatestatus({id, status: 1});
    //     if (res.code === 10000) {
    //         this.$message.success("下架成功");
    //         this.getProductListData();
    //     } else {
    //         this.$message.error(res.message);
    //     }
    // },

    // //删除商品
    // async getDeleteProductData(cid) {
    //     let res = await addelete({id: cid});
    //     if (res.code === 10000) {
    //         this.$message.success("删除成功");
    //         this.getProductListData();
    //     } else {
    //         this.$message.error(res.message);
    //     }
    // },
    //取消关联商户
    openShopMinDetail(e) {
      console.log(e)
      this.selectid = e.id
      this.shopId = e.shopId
      this.isCreateConnectfalse = true
      // this.handleSelect(e.phone,e.uid)
      this.code = e.code
    },

    //取消关联商户
    async getcodedeleteconnect() {
      //取消
      let data = {
        id: this.selectid,
        shopId: this.shopId
      }
      let res = await shopCodeUpdateShopIdDel(data);
      this.$message.success(res.message);
      this.isCreateConnectfalse = false
      this.searchList = []
      this.getProductListData()
    },
    //删除详情
    deleteShopMin(id) {
      this.$confirm('确认删除该商品', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.getDeleteProductData(id);
      }).catch(() => {
        console.log('cancel')
      });

    },

    //获取商品图片
    getFile(file) {
      if (file.files && file.files.length && file.name == 'shopadministration_pic_list') {
        this.img_url = file.files.map(obj => obj.url)
      }
    },

    // 搜索指定商户
    async getStateList(e) {
      console.log(e)
      if (e) {
        let data = {
          id: e
        }
        await sellerList(data).then(res => {
          console.log(res)
          this.stateIdList = res.data.list
        })
      }

    },
  }
};
</script>

<style lang="scss" scoped>
.shopN {
  display: flex;
  align-items: center;
  /*justify-content: space-around;*/
  /*padding: 10px 0;*/
  border-bottom: solid 0.6px #e6e6e6;

  p {
    line-height: 39.59px;
    text-align: center;
  }

  &>p:nth-of-type(1) {
    width: 40%;
    border-right: solid 0.6px #e6e6e6;
  }

  &>p:nth-of-type(2) {
    width: 60%;
  }
}

.ckil:hover {
  cursor: pointer;
}

.search_ {
  padding-left: 20px;
}

.search_q {
  margin-top: 10px;
}

.searchList {
  display: flex;
  align-items: center;
  padding-left: 20px;

  .shop_info_dalog {
    display: flex;
  }

}

.shop {
  padding: 20px;
  position: relative;

  .search {
    float: right;

    .input {
      width: 200px;
    }
  }

  .shop_table_list {
    margin-top: 20px;
  }

  .shop_title {
    font-weight: 700;
  }

  .pagination {
    float: right;
  }

  .status—desc {
    display: inline;
    margin-left: 5px;
  }

  .img_main {
    color: #ffffff;
    background-color: #f4222d;
    width: 60px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 10%;
    margin-left: 30px;
    // z-index: !important;
  }

  .shop_info_dalog {
    margin-top: 20px;
    padding: 0 20px;
  }

  .dialog-footer {
    margin: 20px 0;
    text-align: center;
  }
}
</style>
